﻿@using Newtouch.Infrastructure;
@{
    ViewBag.Title = "MedicalInsuranceApproval";
    Layout = "~/Views/Shared/_Index.cshtml";
}
<style>
    .editable {
        width: 70% !important;
    }
</style>
<div class="gridPanel">
    <table id="gridList"></table>
</div>
<script type="text/javascript">
    var zyh = $.request("zyh");
    var searchTime = $.request("searchTime");
    $(function () {
        initgridList();

        setTimeout(function () {
            $.loading(true, '正在进行明细上传，请稍后...');
            CQmxsc(function () {
                setTimeout(function () {
                    GetApprovalXm();
                });
            });
        },
            50);
    });


    function initgridList() {
        $('#gridList').dataGrid({
            unwritten: false,
            postData: {},
            editurl: "clientArray",
            multiselect: true,
            viewrecords: true,
            height: 350,
            sortable: false,
            colModel: [
                { label: "jfbbh", name: "jfbbh", hidden: true, key: true },
                { label: "jylsh", name: "jylsh", hidden: true },
                { label: "cfh", name: "cfh", hidden: true },
                { label: "审批标记", name: "spbj", width: 90, editable: true, edittype: 'select', editoptions: { value: { 0: "未通过", 1: "通过" } } },
                { label: "费用状态", name: "fyzt", width: 80 },
                { label: "住院号", name: "zyh", width: 80 },
                { label: "项目名称", name: "sfxmmc", width: 100 },
                {
                    label: "开具时间", name: "createtime", width: 120,
                    formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                },
                { label: "单价", name: "dj", width: 60 },
                {
                    label: "数量", name: "sl", width: 60, align: "left", formatter: "number"
                    , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
                {
                    label: "总金额", name: "zje", width: 60, align: "left", formatter: "number"
                    , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
            ],
            gridComplete: function (data) {
                EnableInlineEditBox();
            }
        });
    }

    function CQmxsc(funcSuccCallback) {
        var n = 1;
        var ybzje = 0.00;
        var succTimes = 0;
        var mxnum = 0;
        //每次重新上传，先把以前上传的，但未结算的处方退掉，否则会重复上传
        $.ajax({
            type: "POST",
            url: "/OutpatientManage/OutpatCharge/GetCqyb10Data",
            data: { zymzh: zyh, type: '2' },
            dataType: "json",
            async: false,
            success: function (hcdata) {
                if (hcdata && hcdata.data && hcdata.data.length > 0) {
                    $.each(hcdata.data, function (i, item) {
                        $.ajax({
                            type: "POST",
                            url: "http://127.0.0.1:22222/api/CQYiBao/RefundPrescriptions",
                            data: item,
                            dataType: "json",
                            async: false,
                            success: function (data) {
                                var tfReturn = eval('(' + data + ')');
                                if (tfReturn && tfReturn.Code === "1") {
                                    $.najax({
                                        type: "POST",
                                        data: { zymzh: zyh, cfh: item.cfh },
                                        url: "/OutpatientManage/OutpatCharge/UpDateUploadPrescriptions",
                                        dataType: "json",
                                        async: false,
                                        loading: false,
                                        success: function () {

                                        }
                                    });
                                } else {
                                    $.modalAlert("处方再传，退已上传处方失败：" + tfReturn.ErrorMsg + "此错误可暂时忽略", 'error');
                                }
                            }
                        });
                    });
                }
            }
        });
        for (var i = 0; i < n; i++) {
            $.najax({
                url: "/HospitalizationManage/DischargeSettle/GetCQUploadFeeDetails",
                loading: false,
                async: false,
                type: 'POST',
                data: getSearchCQPostData(i),
                success: function (ajaxResp) {
                    if (ajaxResp && ajaxResp.updata != null) {
                        //ybzje += ajaxResp.ybzje;
                        if (i == 0) {
                            n = ajaxResp.total;
                            mxnum = ajaxResp.records;
                            // zfzje = ajaxResp.zfzje;
                            ///第一次时，先进行删除明细，同时获取到总次数（总条数/10），进行循环调用上传
                            ////每次重新上传，先把以前上传的，但未结算的处方退掉，否则会重复上传
                            //$.ajax({
                            //    type: "POST",
                            //    url: "/OutpatientManage/OutpatCharge/GetCqyb10Data",
                            //    data: { zymzh: zyh, type: '2' },
                            //    dataType: "json",
                            //    async: false,
                            //    success: function (hcdata) {
                            //        if (hcdata && hcdata.data && hcdata.data.length > 0) {
                            //            $.each(hcdata.data, function (i, item) {
                            //                $.ajax({
                            //                    type: "POST",
                            //                    url: "http://127.0.0.1:22222/api/CQYiBao/RefundPrescriptions",
                            //                    data: item,
                            //                    dataType: "json",
                            //                    async: false,
                            //                    success: function (data) {
                            //                        var tfReturn = eval('(' + data + ')');
                            //                        if (tfReturn && tfReturn.Code === "1") {
                            //                            $.najax({
                            //                                type: "POST",
                            //                                data: { zymzh: zyh, cfh: item.cfh },
                            //                                url: "/OutpatientManage/OutpatCharge/UpDateUploadPrescriptions",
                            //                                dataType: "json",
                            //                                async: false,
                            //                                loading: false,
                            //                                success: function () {

                            //                                }
                            //                            });
                            //                        } else {
                            //                            $.modalAlert("处方再传，退已上传处方失败：" + tfReturn.ErrorMsg + "此错误可暂时忽略", 'error');
                            //                        }
                            //                    }
                            //                });
                            //            });
                            //        }
                            //    }
                            //});
                        }
                        //如果有明细需要上传，则调用上传接口
                        if (ajaxResp.updata.cflist.length > 0) {
                            var cfmxjsh = new Array();
                            $.each(ajaxResp.updata.cflist, function (index, value) {
                                var cfArr = new Array();
                                cfArr.push(value);
                                var upDataReturn;// = $.guianyibao.ZyFeemxXr(JSON.stringify(ajaxResp.updata));
                                var ybresp = { zymzh: ajaxResp.updata.zymzh, cflist: cfArr };
                                $.ajax({
                                    type: "POST",
                                    url: "http://127.0.0.1:22222/api/CQYiBao/UploadPrescriptions",
                                    data: ybresp,
                                    dataType: "json",
                                    async: false,
                                    success: function (data) {
                                        upDataReturn = eval('(' + data + ')');
                                        upDataReturn.Data.retCfList[0].cfh = value.cfh;
                                        upDataReturn.Data.retCfList[0].yynm = value.yynm;
                                    }
                                });

                                if (upDataReturn.Code === "1") {
                                    $.najax({
                                        type: "POST",
                                        data: {
                                            entityList: upDataReturn.Data.retCfList, cflist: cfArr, zymzh: ajaxResp.updata.zymzh, jytype: "2"
                                        },
                                        url: "/OutpatientManage/OutpatCharge/SaveChongQingUploadPrescriptions",
                                        dataType: "json",
                                        async: false,
                                        loading: false,
                                        success: function () {

                                        }
                                    });

                                } else {
                                    $.loading(false);
                                    $.modalAlert("处方明细上传失败：" + upDataReturn.ErrorMsg, 'error');
                                    n = 1;//跳出循环
                                    return;
                                }
                            });
                            succTimes++;
                        }

                    } else {
                        $.loading(false);
                        $.modalAlert("医保明细上传失败", 'error');
                        n = 1;//跳出循环
                        return;
                    }
                },
                error: function () {
                    $.loading(false);
                    $.modalAlert("医保明细上传失败", 'error');
                    n = 1;//跳出循环
                    return;
                }
            });
        }

        $.najax({
            type: "GET",
            data: {
                mzzyh:zyh
            },
            url: "/HospitalizationManage/DischargeSettle/GetCQAlreadyUploadFeeDetails",
            dataType: "json",
            async: false,
            loading: false,
            success: function (ajaxResp) {
                ybzje = ajaxResp.ybzje;
            }
        });
        $.loading(false);

        if ((succTimes == n) && funcSuccCallback) {
            setTimeout(function () {
                var mxxx = { mxnum: mxnum, ybzje: ybzje };
                funcSuccCallback(mxxx);
            }, 50);
        }
    }

    //查询条件
    function getSearchCQPostData(n) {
        var pagination = {
            rows: 10,
            page: 1,
            //page: n + 1,
            sidx: ' cxmxlsh asc'
        };
        return { pagination: pagination, zyh: zyh };

    }

    function GetApprovalXm() {
        var parameter1 = { "zyh": zyh, "splx": "1", "rq": searchTime, "xzlb": "1" };
        var parameter2 = { "zyh": zyh, "splx": "2", "rq": searchTime, "xzlb": "1" };
        var spGsfReturn = {};
        var spBdbReturn = {};
        $.ajax({
            loading: "正在进行未审批项目查询，请稍后...",
            type: "POST",
            url: "http://127.0.0.1:22222/api/CQYiBao/GetApprovalXm",
            data: parameter1,
            dataType: "json",
            async: false,
            success: function (data) {
                spGsfReturn = eval('(' + data + ')');
            }
        });

        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:22222/api/CQYiBao/GetApprovalXm",
            data: parameter2,
            dataType: "json",
            async: false,
            success: function (data) {
                spBdbReturn = eval('(' + data + ')');
            }
        });

        var Gsfcfmxlshstr ="";
        var Bdbcfmxlshstr="";
        if (!!spGsfReturn && !!spBdbReturn && spGsfReturn.Code === "1" && spBdbReturn.Code === "1") {
            if (!!spGsfReturn.Data && spGsfReturn.Data.cfmxlshList.length > 0) {
                $.loading(false);
                Gsfcfmxlshstr = spGsfReturn.Data.cfmxlshList.map(p => p.cfmxlsh).join(",")+'';
            }
            if (!!spBdbReturn.Data && spBdbReturn.Data.cfmxlshList.length > 0) {
                $.loading(false);
                Bdbcfmxlshstr = spBdbReturn.Data.cfmxlshList.map(p => p.cfmxlsh).join(",") + '';
            }
            var cfmxlshstr = Gsfcfmxlshstr + Bdbcfmxlshstr + '';
            $("#gridList").jqGrid('setGridParam', {
                url: "/HospitalizationManage/DischargeSettle/GetUnapproveddetails?cfmxlshstr=" + cfmxlshstr + "&zyh=" + zyh,
            }).trigger('reloadGrid');
        } else {
            $.loading(false);
            $.modalAlert("调用医保22接口失败", 'error');
            return;
        }
    }

    //启用行内编辑
    function EnableInlineEditBox() {
        var ids = $("#gridList").getDataIDs();
        if (ids.length > 0) {
            $.each(ids, function () {
                var rowid = String(this);
                //打开编辑模式
                $("#gridList").jqGrid('editRow', rowid, true, null, null, null, null, function (callbackRowId) {     //true: when set to true we can use [Enter] key to save the row and [Esc] to cancel editing.
                });
            });
        }
    }

    function submitform() {
        //获取选中行Id
        var selRowIds = $("#gridList").jqGrid('getGridParam', 'selarrrow');
        if (selRowIds.length === 0) {
            $.modalAlert("请先选中需审批的信息", 'warning');
            return;
        }
        var rowIds = $("#gridList").jqGrid('getDataIDs');
        for (var i = 0; i < rowIds.length; i++) {
            var saveResult = $("#gridList").saveRow(rowIds[i], null, null, null, function (callbackRowId) { }, null, null);

            if (!saveResult) {
                EnableInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                return;   //保存失败，则return
            }
        }

        var flag = false;
        var gridListData = $("#gridList").jqGrid('getRowData_AllLine', null, true);
        if (gridListData.length < 1) {
            $.modalAlert("当前没有保存的审批内容", 'warning');
            return;
        }


        if (flag) {
            EnableInlineEditBox();
            return;
        }
        var cfhlist = [];
        $.each(gridListData, function () {    //去掉action
            for (var i = 0; i < $(this).length; i++) {
                if (this.spbj == undefined || this.spbj == "" || this.spbj == "请选择") {
                    $.modalAlert("审批标识未选择", "warning");
                    flag = true;
                    return false;
                }

                var postdata = { zyh: zyh, cfmxlsh: $(this)[i].jylsh, spbj: $(this)[i].spbj == "未通过" ? "0" : "1", xzlb: "1" }
                var cfh = $(this)[i].cfh;
                //21接口：医保高收费(高蛋白)费用审批
                $.ajax({
                    type: "POST",
                    url: "http://127.0.0.1:22222/api/CQYiBao/HighfeesExamination",
                    data: postdata,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        var tfReturn = eval('(' + data + ')');
                        if (tfReturn && tfReturn.Code === "1") {
                            cfhlist.push(cfh);
                        } else {
                            $.modalAlert("医保高收费(高蛋白)费用审批失败：" + tfReturn.ErrorMsg + "此错误可暂时忽略", 'error');
                        }
                    }
                });
            }
        });

        if (flag) {
            EnableInlineEditBox();
            return;
        }

        $.ajax({
            type: "POST",
            url: "/HospitalizationManage/DischargeSettle/updatespbz?cfhstr=" + cfhlist.join(','),
            dataType: "json",
            async: false,
            success: function (data) {
                if (data && data.state === "success") {
                    $.modalClose();
                    //GetApprovalXm();
                } else {
                    $.modalAlert("cqyb_OutPutInPar04更新审批标志失败：" + tfReturn.ErrorMsg, 'error');
                }
            }
        });
    };
</script>

